package earogya.ehr.patient_details.messages;

import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import ca.uhn.hl7v2.HL7Exception;
import ca.uhn.hl7v2.model.DataTypeException;
import ca.uhn.hl7v2.model.v251.datatype.DT;
import ca.uhn.hl7v2.model.v251.datatype.DTM;
import ca.uhn.hl7v2.model.v251.datatype.ST;
import ca.uhn.hl7v2.model.v251.datatype.XAD;
import ca.uhn.hl7v2.model.v251.datatype.XPN;
import ca.uhn.hl7v2.model.v251.datatype.XTN;
import ca.uhn.hl7v2.model.v251.message.ADT_A01;
import ca.uhn.hl7v2.model.v251.segment.AL1;
import ca.uhn.hl7v2.model.v251.segment.PID;
import ca.uhn.hl7v2.model.v251.segment.PD1;
import ca.uhn.hl7v2.model.v251.segment.DB1;
import ca.uhn.hl7v2.model.v251.datatype.TS;
import earogya.ehr.patient_details.*;

public class ADT_A04_Handler {
	private ADT_A01 adtMsg;
	Patient patient=new Patient();
	private PatientAddress pAddress;
	private PatientDisability pDisability;
	private PatientEmail pEmail;
	private PatientTelephone pTelephone;
	private PatientAllergy pAllergy;
	private HibernateManager hibernateManager=new HibernateManager();


	
	public ADT_A04_Handler(ADT_A01 adtMsg){
		this.adtMsg=adtMsg;
	}
	
	/**
	 * Identify separate segments in the message and add the details in the
	 * segments to their respective POJO classes
	 * @return - the acknowledgement of the HL7 message
	 * @throws HL7Exception
	 * @throws IOException
	 */
	public String manageMessage() throws HL7Exception, IOException{
		this.patient.setPatientId(this.enterPatientDetails());
		this.enterPatientAddressDetails();
		this.enterPatientDisabilityDetails();
		this.enterPatientEmailAndTelephoneDetails();
		this.entereAllergyDetails();
		String ack=adtMsg.generateACK().encode();
		return ack;
	}
	
	public int enterPatientDetails() throws HL7Exception{
		try{
		PID pid=adtMsg.getPID();
		PD1 pd1=adtMsg.getPD1();
		XPN pName=pid.getPatientName(0);
		patient.setPrefix(pName.getPrefixEgDR().getValue());
		patient.setGivenName(pName.getGivenName().getValue());
		patient.setFamilyName(pName.getFamilyName().getSurname().getValue());
		patient.setNicNo(pid.getPatientIdentifierList(0).getIDNumber().getValue());
		patient.setGender(pid.getAdministrativeSex().toString());
		//patient.setBirthTime(pid.getDateTimeOfBirth().getTime().getValueAsDate());
		//System.out.print(pid.getPatientDeathDateAndTime());
		System.out.print(pid.getDateTimeOfBirth().getTime().getValueAsDate());
		if(pid.getDateTimeOfBirth().getTime().getValue()==null){}
		else{
			patient.setBirthTime(pid.getDateTimeOfBirth().getTime().getValueAsDate());
		}
		patient.setBirthPlaceAddress(pid.getBirthPlace().toString());
		patient.setMultipleBirthIndex((pid.getMultipleBirthIndicator().getValue()==null)?0:Short.valueOf(pid.getMultipleBirthIndicator().getValue()));
		patient.setMultipleBirthOrderNumber((pid.getBirthOrder().getValue()==null)?0:Short.valueOf(pid.getBirthOrder().getValue()));
		patient.setOrganDonorIndex((pd1.getOrganDonorCode().getValue()==null)?0:Integer.valueOf(pd1.getOrganDonorCode().getValue()));
		patient.setMaritialStatus(pid.getMaritalStatus().getText().toString());
		patient.setLivingArrangementId((pd1.getLivingArrangement().getValue()==null)?0:Integer.valueOf(pd1.getLivingArrangement().getValue()));
		patient.setEthnicGroupId(pid.getEthnicGroup(0).getText().toString());
		patient.setReligiousAffliationId(pid.getReligion().getText().toString());
		patient.setDeceasedIndex(false);
		patient.setIsActive(true);
		
		}
		catch(Exception e){
			e.printStackTrace();
		}
		return hibernateManager.saveObject(patient);
		
	}
	
	private void enterPatientAddressDetails()throws HL7Exception{
		PID pid=adtMsg.getPID();
		XAD[] addressList=pid.getPatientAddress();
		for(int i=0;i<addressList.length;i++){
			pAddress=new PatientAddress();
			pAddress.setPatientId(this.patient.getPatientId());
			pAddress.setCity1(addressList[i].getOtherDesignation().getValue());
			pAddress.setCountry(addressList[i].getCountry().getValue());
			pAddress.setHouseNumber(addressList[i].getStreetAddress().getDwellingNumber().getValue());
			pAddress.setCity2(addressList[i].getCity().getValue());
			pAddress.setStreet(addressList[i].getStreetAddress().getStreetName().getValue());
			System.out.print(addressList[i].getStreetAddress().getDwellingNumber().getValue());
			hibernateManager.saveObject(pAddress);
		}		
	}
	
	private void enterPatientDisabilityDetails() throws DataTypeException{
		DB1 db1;
		int db1Repetitions=adtMsg.getDB1Reps();
		for(int i=0;i<db1Repetitions;i++){
			db1=adtMsg.getDB1(i);
			pDisability=new PatientDisability();
			pDisability.setPatientId(this.patient.getPatientId());
			pDisability.setDisabilityId(Integer.parseInt(db1.getDisabledIndicator().getValue()));
			if(db1.getDisabilityStartDate()==null){}
			else{
				pDisability.setDisabilityStartDate(this.dtToDate(db1.getDisabilityStartDate()));
			}
			if(db1.getDisabilityEndDate()==null){}
			else{
				pDisability.setDisabilityEndDate(this.dtToDate(db1.getDisabilityEndDate()));
			}	
			hibernateManager.saveObject(pDisability);
		}
	}
	
	private void enterPatientEmailAndTelephoneDetails(){
		PID pid=adtMsg.getPID();
		int i=0;
		while(!(pid.getPhoneNumberHome(i).getTelephoneNumber().getValue()==null)||!(pid.getPhoneNumberHome(i).getEmailAddress().getValue()==null)){
			
			if(pid.getPhoneNumberHome(i).getTelephoneNumber().getValue()==null){}
			else{
			pTelephone=new PatientTelephone();
			pTelephone.setPatientId(this.patient.getPatientId());
			pTelephone.setTelephoneNo(pid.getPhoneNumberHome(i).getTelephoneNumber().getValue());
			hibernateManager.saveObject(pTelephone);
			}
			if(pid.getPhoneNumberHome(i).getEmailAddress().getValue()==null){}
			else{
				System.out.print("email"+pid.getPhoneNumberHome(i).getEmailAddress().getValue());
			pEmail=new PatientEmail();
			pEmail.setPatientId(this.patient.getPatientId());
			pEmail.setEmail(pid.getPhoneNumberHome(i).getEmailAddress().getValue());
			hibernateManager.saveObject(pEmail);
			}
			i++;
		}
	
	}
	
	private void entereAllergyDetails() throws DataTypeException{
		AL1 al1;
		for(int i=0;i<adtMsg.getAL1Reps();i++){
			al1=adtMsg.getAL1(i);
			pAllergy=new PatientAllergy();
			pAllergy.setAllergyCode(al1.getAllergenCodeMnemonicDescription().getComponent(0).toString());
			pAllergy.setPatientId(this.patient.getPatientId());
			pAllergy.setSeverity(al1.getAllergySeverityCode().getComponent(0).toString());
			pAllergy.setIdentificationDate(this.dtToDate(al1.getAl16_IdentificationDate()));
			System.out.print(al1.getAllergenCodeMnemonicDescription().getComponent(0).toString());
			hibernateManager.saveObject(pAllergy);
		}
	}
		
	private Date dtToDate(DT dtDate) throws DataTypeException{
		Calendar cal=Calendar.getInstance();
		cal.set(dtDate.getYear(), dtDate.getMonth(), dtDate.getDay());
		return cal.getTime();
	}
	
}
